<template>
  <div class="order-apply-invoice">
    <div ref="chartContainer" class="chart-container"></div>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, onBeforeUnmount, watch, ref,nextTick } from 'vue'
import * as echarts from 'echarts'
const emits = defineEmits(['barClick'])

const props = defineProps({
  config: {
    type: Object,
    required: true,
    default: () => ({
      xAxisData: [],
      yAxisDataBar: [],
      yAxisDataLine: [],
      legendData:[]
    })
  }
})

const chartContainer = ref<HTMLElement | null>(null)
let chartInstance: echarts.ECharts | null = null

// 初始化图表
const initChart = () => {
  if (!chartContainer.value) return
  
  // 销毁现有实例
  if (chartInstance) {
    chartInstance.dispose()
  }
  
  // 创建新实例
  chartInstance = echarts.init(chartContainer.value)
    // 添加点击事件监听
  chartInstance.on('click', 'series.bar', (params) => {
    // params 包含点击的柱状图数据信息
    emits('barClick', params )
  })
  updateChart()
}

// 更新图表配置
const updateChart = () => {
  if (!chartInstance || !props.config) return

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        crossStyle: { color: '#999' }
      }
    },
    legend: {
      right: '120px',
      top: '30px',
      data: [ props.config.legendData[0] || '已提箱量（个）', props.config.legendData[1] || '已提箱量占比（%）']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: [...props.config.xAxisData],
      axisPointer: { type: 'shadow' },
      // axisLabel: {
      //   rotate: 30, // 标签旋转防止重叠
      //   interval: 0 // 强制显示所有标签
      // }
    },
    yAxis: [
      {
        type: 'value',
        name: '箱量',
        min: 0,
        // max: 250,
        interval: 100,
        axisLabel: { formatter: '{value}个' },
        axisLine: { show: true },
        splitLine: { show: false }
      },
      {
        type: 'value',
        name: '占比',
        min: 0,
        // max: 100,
        interval: 20,
        z: 2,
        axisLabel: { formatter: '{value}%' },
        axisLine: { show: true }
      }
    ],
    series: [
      {
        name:  props.config.legendData[0] || '已提箱量（个）',
        type: 'bar',
        barWidth: '60%',
        itemStyle: {
          color: '#5470C6' // 设置柱状图颜色
        },
        tooltip: {
          valueFormatter: (value: number) => `${value}个`
        },
        data: Array.from(props.config.yAxisDataBar)
      },
      {
        name: props.config.legendData[1] || '已提箱量占比（%）',
        type: 'line',
        yAxisIndex: 1, // 使用第二个Y轴
        symbol: 'circle',
        smooth: true, // 平滑曲线
        symbolSize: 8,
        itemStyle: {
          color: '#EE6666' // 设置折线图颜色
        },
        tooltip: {
          valueFormatter: (value: number) => `${value}%`
        },
        data:Array.from(props.config.yAxisDataLine)
      }
    ]
  }
  chartInstance.setOption(option)
}


onMounted(() => {
  nextTick(()=>{
    initChart()
  })
})

onBeforeUnmount(() => {
  // 清理资源
  if (chartInstance) {
    chartInstance.dispose()
    chartInstance = null
  }
})

// 监听配置变化
watch(() => props.config,() => {
    if (!chartInstance) {
      initChart()
    } else {
      updateChart()
    }
  },
  { deep: true, immediate: true }
)
</script>

<style lang="scss" scoped>
.order-apply-invoice {
  width: 100%;
  height: 100%;
  
  .chart-container {
    width: 100%;
    height: 100%;
    min-height: 400px; // 确保最小高度
  }
}
</style>